//
//  SZLAccountHelper.m
//  Shengzhuli
//
//  Created by 卡忙科技 on 16/7/29.
//  Copyright © 2016年 kamangkeji. All rights reserved.
//

#import "SZLAccountHelper.h"
#import "ConLoginViewController.h"
#import "ConNavigationontroller.h"

@implementation SZLAccountHelper

+ (instancetype)shareInstance
{
    static SZLAccountHelper *instance = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        instance = [[SZLAccountHelper alloc] init];
    });
    return instance;
}

+ (BOOL)isAlreadyLogin
{
    NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
    NSDictionary *userInfo = [userDefaults objectForKey:User_Json];
    return ([userInfo[@"token"] length]>0);
}

+ (void)loadAlreadyInfo
{
    NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
    if ([userDefaults objectForKey:User_Json]!=nil) {
        [self updateUserWithLogin:[userDefaults objectForKey:User_Json] needSave:NO];
    }
}

+ (void)clearAlreadyInfo
{
    NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
    [userDefaults setObject:nil forKey:User_Json];
    [userDefaults synchronize];
    [SZLAccountHelper shareInstance].token = @"";
    //环信退出
    [[EMClient sharedClient] logout:YES completion:^(EMError *aError) {
        if (!aError) {
            NSLog(@"环信退出成功");
        }
    }];
}


+ (void)updateUserWithLogin:(NSDictionary *)json needSave:(BOOL)needSave
{
    if (needSave) {
        NSUserDefaults *userDefaults =[NSUserDefaults standardUserDefaults];
        [userDefaults setObject:json forKey:User_Json];
        [userDefaults synchronize];
    }
    SZLAccountHelper *account = [SZLAccountHelper shareInstance];
    account.token = json[@"token"];
    account.roleId = [json[@"roleId"] integerValue];
    account.HXpwd = json[@"HXpwd"];
    account.mobilePhone = json[@"mobilePhone"];
}

+ (BOOL)shouldLogin
{
    BOOL isLogin = [self isAlreadyLogin];
    if (!isLogin) {
        ConLoginViewController *loginVc = [[ConLoginViewController alloc]init];
        ConNavigationontroller *nav = [[ConNavigationontroller alloc]initWithRootViewController:loginVc];
        UIViewController *vc = [UIApplication sharedApplication].keyWindow.rootViewController;
        [vc presentViewController:nav animated:YES completion:nil];
        return YES;
    }
    return NO;
}
- (NSString *)token
{
    if ([SZLAccountHelper shouldLogin]) {
        return nil;
    }
    return _token;
}

@end
